/****************************************************************************
* VCGLib                                                            o o     *
* Visual and Computer Graphics Library                            o     o   *
*                                                                _   O  _   *
* Copyright(C) 2004                                                \/)\/    *
* Visual Computing Lab                                            /\/|      *
* ISTI - Italian National Research Council                           |      *
*                                                                    \      *
* All rights reserved.                                                      *
*                                                                           *
* This program is free software; you can redistribute it and/or modify      *   
* it under the terms of the GNU General Public License as published by      *
* the Free Software Foundation; either version 2 of the License, or         *
* (at your option) any later version.                                       *
*                                                                           *
* This program is distributed in the hope that it will be useful,           *
* but WITHOUT ANY WARRANTY; without even the implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)          *
* for more details.                                                         *
*                                                                           *
****************************************************************************/
#ifndef __VCGLIB_BOX4
#define __VCGLIB_BOX4

#include <vcg/space/point4.h>
#include <vcg/space/box3.h>
#include <vcg/math/matrix44.h>
#include <vcg/space/line3.h>
#include <vcg/space/plane3.h>

namespace vcg {

/** \addtogroup space */
/*@{*/
/** 
Templated class for 4D boxes.
  This is the class for definition of a axis aligned bounding box in 4D space. It is stored just as two Point4
	@param BoxScalarType (template parameter) Specifies the type of scalar used to represent coords.
*/
template <class BoxScalarType>
class Box4
{
public:

	/// The scalar type
	typedef BoxScalarType ScalarType;

	/// min coordinate point
  Point4<BoxScalarType> min;
	/// max coordinate point
        Point4<BoxScalarType> max;
		/// The bounding box constructor
        inline  Box4() { min.X()= 1;max.X()= -1;min.Y()= 1;max.Y()= -1;min.Z()= 1;max.Z()= -1;min.W()= 1;max.W()= -1;}
		/// Copy constructor
        inline  Box4( const Box4 & b ) { min=b.min; max=b.max; }
		/// Min Max constructor
        inline  Box4( const Point4<BoxScalarType> & mi, const Point4<BoxScalarType> & ma ) { min = mi; max = ma; }
    /// Point Radius Constructor
  inline Box4(const Point4<BoxScalarType> & center, const BoxScalarType & radius) {
    min = center-Point4<BoxScalarType>(radius,radius,radius);
    max = center+Point4<BoxScalarType>(radius,radius,radius);
  }
		/// The bounding box distructor
        inline ~Box4() { }
		/// Operator to compare two bounding box
        inline bool operator == ( Box4<BoxScalarType> const & p ) const
	{
		return min==p.min && max==p.max;
	}
		/// Operator to dispare two bounding box
        inline bool operator != ( Box4<BoxScalarType> const & p ) const
	{
		return min!=p.min || max!=p.max;
	}
		/** Varia le dimensioni del bounding box scalandole rispetto al parametro scalare.
			@param s Valore scalare che indica di quanto deve variare il bounding box
		*/
	void Offset( const BoxScalarType s )
	{
                Offset( Point4<BoxScalarType> (s,s,s));
	}
		/** Varia le dimensioni del bounding box del valore fornito attraverso il parametro.
                        @param delta Point in 4D space
		*/
        void Offset( const Point4<BoxScalarType> & delta )
	{
		min -= delta;
		max += delta;
	}
		/// Initializing the bounding box
        void Set( const Point4<BoxScalarType> & p )
	{
		min = max = p;
	}
		/// Set the bounding box to a null value
	void SetNull()
	{
		min.X()= 1; max.X()= -1;
		min.Y()= 1; max.Y()= -1;
		min.Z()= 1; max.Z()= -1;
                min.W()= 1; max.W()= -1;
	}
		/** Function to add two bounding box
			@param b Il bounding box che si vuole aggiungere
		*/
        void Add( Box4<BoxScalarType> const & b )
	{
		if(b.IsNull()) return; // Adding a null bbox should do nothing
		if(IsNull()) *this=b;
		else
		{
			if(min.X() > b.min.X()) min.X() = b.min.X();
			if(min.Y() > b.min.Y()) min.Y() = b.min.Y();
			if(min.Z() > b.min.Z()) min.Z() = b.min.Z();
                        if(min.W() > b.min.W()) min.W() = b.min.W();

			if(max.X() < b.max.X()) max.X() = b.max.X();
			if(max.Y() < b.max.Y()) max.Y() = b.max.Y();
			if(max.Z() < b.max.Z()) max.Z() = b.max.Z();
                        if(max.W() < b.max.W()) max.W() = b.max.W();
		}
	}
		/** Funzione per aggiungere un punto al bounding box. Il bounding box viene modificato se il punto
			cade fuori da esso.
                        @param p The point 4D
		*/
        void Add( const Point4<BoxScalarType> & p )
	{
		if(IsNull()) Set(p);
		else 
		{
			if(min.X() > p.X()) min.X() = p.X();
			if(min.Y() > p.Y()) min.Y() = p.Y();
			if(min.Z() > p.Z()) min.Z() = p.Z();
                        if(min.W() > p.W()) min.W() = p.W();

			if(max.X() < p.X()) max.X() = p.X();
			if(max.Y() < p.Y()) max.Y() = p.Y();
			if(max.Z() < p.Z()) max.Z() = p.Z();
                        if(max.W() < p.W()) max.W() = p.W();
		}
	}
	
	// Aggiunge ad un box un altro box trasformato secondo la matrice m
        void Add( const Matrix44<BoxScalarType> &m, const Box4<BoxScalarType> & b )
	{
                        const Point4<BoxScalarType> &mn= b.min;
                        const Point4<BoxScalarType> &mx= b.max;
                        Add(m*(Point4<BoxScalarType>(mn[0],mn[1],mn[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mx[0],mn[1],mn[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mn[0],mx[1],mn[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mx[0],mx[1],mn[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mn[0],mn[1],mx[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mx[0],mn[1],mx[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mn[0],mx[1],mx[2], mn[3])));
                        Add(m*(Point4<BoxScalarType>(mx[0],mx[1],mx[2], mn[3])));
	}
		/** Calcola l'intersezione tra due bounding box. Al bounding box viene assegnato il valore risultante.
			@param b Il bounding box con il quale si vuole effettuare l'intersezione
		*/
        void Intersect( const Box4<BoxScalarType> & b )
	{
		if(min.X() < b.min.X()) min.X() = b.min.X();
		if(min.Y() < b.min.Y()) min.Y() = b.min.Y();
		if(min.Z() < b.min.Z()) min.Z() = b.min.Z();
                if(min.W() < b.min.W()) min.W() = b.min.W();

		if(max.X() > b.max.X()) max.X() = b.max.X();
		if(max.Y() > b.max.Y()) max.Y() = b.max.Y();
		if(max.Z() > b.max.Z()) max.Z() = b.max.Z();
                if(max.W() > b.max.W()) max.W() = b.max.W();

                if(min.X()>max.X() || min.Y()>max.Y() || min.Z()>max.Z() || min.W()>max.W()) SetNull();
	}
		/** Trasla il bounding box di un valore definito dal parametro.
			@param p Il bounding box trasla sulla x e sulla y in base alle coordinate del parametro
		*/
        void Translate( const Point4<BoxScalarType> & p )
	{
		min += p;
		max += p;
	}
		/** Verifica se un punto appartiene ad un bounding box.
                        @param p The point 4D
			@return True se p appartiene al bounding box, false altrimenti
		*/
        bool IsIn( Point4<BoxScalarType> const & p ) const
	{
		return (
			min.X() <= p.X() && p.X() <= max.X() &&
			min.Y() <= p.Y() && p.Y() <= max.Y() &&
                        min.Z() <= p.Z() && p.Z() <= max.Z() &&
                            min.W() <= p.W() && p.W() <= max.W()
		);
	}
		/** Verifica se un punto appartiene ad un bounding box aperto sul max.
                        @param p The point 4D
			@return True se p appartiene al bounding box, false altrimenti
		*/
        bool IsInEx( Point4<BoxScalarType> const & p ) const
	{
		return (
			min.X() <= p.X() && p.X() < max.X() &&
			min.Y() <= p.Y() && p.Y() < max.Y() &&
                        min.Z() <= p.Z() && p.Z() < max.Z() &&
                            min.W() <= p.W() && p.W() < max.W()
		);
	}
		/** Verifica se due bounding box collidono cioe' se hanno una intersezione non vuota. Per esempio
			due bounding box adiacenti non collidono.
			@param b A bounding box
			@return True se collidoo, false altrimenti
		*/
	/* old version
        bool Collide(Box4<BoxScalarType> const &b)
	{
                Box4<BoxScalarType> bb=*this;
		bb.Intersect(b);
		return bb.IsValid();
	}
	*/
        bool Collide(Box4<BoxScalarType> const &b) const
	{
		return b.min.X()<max.X() && b.max.X()>min.X() &&
			   b.min.Y()<max.Y() && b.max.Y()>min.Y() &&
                           b.min.Z()<max.Z() && b.max.Z()>min.Z() &&
                        b.min.W()<max.W() && b.max.W()>min.W() ;
	}
		/** Controlla se il bounding box e' nullo.
			@return True se il bounding box e' nullo, false altrimenti
		*/
        bool IsNull() const { return min.X()>max.X() || min.Y()>max.Y() || min.Z()>max.Z() || min.W()>max.W() ; }
		/** Controlla se il bounding box e' vuoto.
			@return True se il bounding box e' vuoto, false altrimenti
		*/
	bool IsEmpty() const { return min==max; }
		/// Restituisce la lunghezza della diagonale del bounding box.
	BoxScalarType Diag() const
	{
		return Distance(min,max);
	}
		/// Calcola il quadrato della diagonale del bounding box.
	BoxScalarType SquaredDiag() const
	{
		return SquaredDistance(min,max);
	}
		/// Calcola il centro del bounding box.
        Point4<BoxScalarType> Center() const
	{
		return (min+max)/2;
	}
		/// Compute bounding box size.
        Point4<BoxScalarType> Dim() const
	{
		return (max-min);
	}
          /// Returns global coords of a local point expressed in [0..1]^4
        Point4<BoxScalarType> LocalToGlobal(Point4<BoxScalarType> const & p) const{
                return Point4<BoxScalarType>(
                            min[0] + p[0]*(max[0]-min[0]),
                            min[1] + p[1]*(max[1]-min[1]),
                            min[2] + p[2]*(max[2]-min[2]),
                            min[3] + p[3]*(max[3]-min[3]));
	}
          /// Returns local coords expressed in [0..1]^4 of a point in 4D
        Point4<BoxScalarType> GlobalToLocal(Point4<BoxScalarType> const & p) const{
            return Point4<BoxScalarType>(
                        (p[0]-min[0])/(max[0]-min[0]),
                        (p[1]-min[1])/(max[1]-min[1]),
                        (p[2]-min[2])/(max[2]-min[2]),
                        (p[3]-min[3])/(max[3]-min[3]) );
	}
		/// Calcola il volume del bounding box.
	BoxScalarType Volume() const
	{
                return (max.X()-min.X())*(max.Y()-min.Y())*(max.Z()-min.Z())*(max.W()-min.W());
	}
        /// Calcola la dimensione del bounding box sulla x.
        inline BoxScalarType DimX() const { return max.X()-min.X();}
        /// Calcola la dimensione del bounding box sulla y.
        inline BoxScalarType DimY() const { return max.Y()-min.Y();}
        /// Calcola la dimensione del bounding box sulla z.
        inline BoxScalarType DimZ() const { return max.Z()-min.Z();}
        /// Calcola la dimensione del bounding box sulla w.
        inline BoxScalarType DimW() const { return max.W()-min.W();}
        /// Calcola il lato di lunghezza maggiore
	inline unsigned char MaxDim() const { 
                int i, mdim = 0;
                Point4<BoxScalarType> diag = max-min;
                for (i=1; i<4; i++)
                {
                    if (diag[i]>diag[mdim])
                        mdim = i ;
                }
                return mdim ;
	}
		/// Calcola il lato di lunghezza minore  
	inline unsigned char MinDim() const { 
                int i, mdim = 0;
                Point4<BoxScalarType> diag =  max-min;
                for (i=1; i<4; i++)
                {
                    if (diag[i]<diag[mdim])
                        mdim = i ;
                }
                return mdim ;
	}

	template <class Q>
        inline void Import( const Box4<Q> & b )
	{
		min.Import(b.min);
		max.Import(b.max);
	}

        template <class Q>
        inline void Import( const Box3<Q> & b, Q & minw, Q & maxw )
        {
            min.Import(Point4<BoxScalarType>(b.min[0], b.min[1], b.min[2], minw)) ;
            max.Import(Point4<BoxScalarType>(b.max[0], b.max[1], b.max[2], maxw)) ;
        }

	template <class Q>
        static inline Box4 Construct( const Box4<Q> & b )
	{
    return Box4(Point4<BoxScalarType>::Construct(b.min),Point4<BoxScalarType>::Construct(b.max));
	}
		

                /// gives the ith box vertex in order: (x,y,z,w),(X,y,z,w),(x,Y,z,w),(X,Y,z,w),(x,y,Z,w),(X,y,Z,w),(x,Y,Z,w),(X,Y,Z,w) ...
        Point4<BoxScalarType> P(const int & i) const {
            return Point4<BoxScalarType>(
                        min[0]+ (i & 1) * DimX(),
                        min[1]+ ((i>>1) & 1) * DimY(),
                        min[2]+ ((i>>2) & 1)* DimZ(),
                        min[3]+ ((i>>3) & 1)* DimW() );
	}
}; // end class definition

//template <class T> Box4<T> Point4<T>::GetBBox(Box4<T> &bb) const {
// bb.Set( *this );
//}
 

typedef Box4<short>  Box4s;
typedef Box4<int>	 Box4i;
typedef Box4<float>  Box4f;
typedef Box4<double> Box4d;


/*@}*/

} // end namespace
#endif

